package com.practice;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class ExerciseTransfer {

    public static void main(String[] args) throws InterruptedException {

        long l = System.currentTimeMillis();

        Account a = new Account(1000, "a");
        Account b = new Account(1000, "b");
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
                log.debug("已完成{}次转账", i);
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
                log.debug("已完成{}次转账", i);

            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        log.debug("total:{}，耗时：{}秒", (a.getMoney() + b.getMoney()), (System.currentTimeMillis() - l) / 1000);
    }

    // Random 为线程安全
    static Random random = new Random(); // 随机 1~100

    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}
